package com.github.postsanf.yinian.huanxin.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.postsanf.yinian.ElseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.AlertNameActivity;
import com.github.postsanf.yinian.adapter.ChatMemberAdapter;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.bean.YNMember;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.huanxin.Constant;
import com.github.postsanf.yinian.service.AlbumContentService;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.WrapContentGridLayoutManager;
import com.github.postsanf.yinian.view.SpacesItemDecoration;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by Administrator on 2016/9/22.
 */
public class ChatMemberActivity extends ElseActivity implements View.OnClickListener {
    private RelativeLayout all_member_zonename_view;
    private RelativeLayout all_member_history_view;
    private RecyclerView rv_home_album;              // 列表视图
    private ChatMemberAdapter mAdapter;                   // 适配器
    private List<YNMember> mMemberDatas;               // 成员数据
    private TextView all_member_zonename;
    private String chatName;
    private YNAlbum curAlbum;
    private String albumName_alert;
    private int mGroupId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.easechat_member_list);
        registerBoradcastReceiver();
        mMemberDatas = new ArrayList<>();
        noticeServiceInit();
        initView();
    }

    private void initView() {
        curAlbum = YNSingleton.getInstance().getCurAlbum();
        if (curAlbum != null) {
            mGroupId = curAlbum.getGroupid();
        } else {
            mGroupId = application.getCurGid();
        }
        chatName = application.getCurUser().getUnickname();
        findViewById(R.id.chatmember_back).setOnClickListener(this);
        all_member_zonename_view = (RelativeLayout) findViewById(R.id.all_member_zonename_view);
        all_member_history_view = (RelativeLayout) findViewById(R.id.all_member_history_view);
        all_member_zonename_view.setOnClickListener(this);
        all_member_history_view.setOnClickListener(this);
        all_member_zonename = (TextView) findViewById(R.id.all_member_zonename);
        if (!StringUtils.isEmpty(chatName)) {
            all_member_zonename.setText(chatName);
        }
        rv_home_album = (RecyclerView) findViewById(R.id.rv_chatmember_album);
        rv_home_album.setLayoutManager(new WrapContentGridLayoutManager(this, 4));
        // 设置适配器
        mAdapter = new ChatMemberAdapter(this, mMemberDatas, YNSingleton.getInstance().getCurAlbum());
        rv_home_album.setAdapter(mAdapter);
        rv_home_album.setHasFixedSize(true);
        rv_home_album.setItemViewCacheSize(50);
        //设置item之间的间隔
        SpacesItemDecoration decoration = new SpacesItemDecoration(4);
        rv_home_album.addItemDecoration(decoration);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.chatmember_back:
                finish();
                break;
            case R.id.all_member_zonename_view:
                String tab = getString(R.string.numberofme);
                if (StringUtils.isOfficialGroup(curAlbum.getGtype()) && !(String.valueOf(application.getCurID()).equals(tab))) {
                    return;
                }
                Intent intent = new Intent(this, AlertNameActivity.class);
                intent.putExtra(CommonConstants.YNDATAS, all_member_zonename.getText().toString());
                startActivityForResult(intent, CommonConstants.REQ_ALERT_GNAME);
                break;
            case R.id.all_member_history_view:
                String gimid = getIntent().getStringExtra("gimid");
                if (!StringUtils.isEmpty(gimid)) {
                    Intent chatIntent = new Intent(ChatMemberActivity.this, ChatHistoryActivity2.class);
                    chatIntent.putExtra("chatType", Constant.CHATTYPE_GROUP);
                    chatIntent.putExtra("userId", gimid);
                    startActivity(chatIntent);
                }
                break;


        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //  修改昵称回调
            case CommonConstants.REQ_ALERT_GNAME:
                if (resultCode == RESULT_CANCELED) {
                    return;
                }
                    albumName_alert = data.getStringExtra(CommonConstants.REQ_DATA);
                    all_member_zonename.setText(albumName_alert);
                    alertRemarkName(mGroupId, application.getCurID(), application.getCurID(), albumName_alert);
                break;
            default:
                break;
        }
    }

    // 修改昵称名
    private void alertRemarkName(int mGroupId, int from, int to, String name) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(mGroupId));
        mParam.put(CommonConstants.FROM, String.valueOf(from));
        mParam.put(CommonConstants.TO, String.valueOf(to));
        mParam.put(CommonConstants.Name, name);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.NoteUserInSpace)).setMethod(HttpMethods.Post).setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resAlertGroupName = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resAlertGroupName.getCode())) {
                            sendBroadcast(new Intent(ACTIONs.actionNoteNameUpdate));
                            showToast("修改成功");
                        } else {
                            showToast("修改失败");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 更新成员数据
    private void updateView(List<YNMember> memberList) {
        mMemberDatas.clear();
        mMemberDatas.addAll(memberList);
        YNMember ynMember = new YNMember();
        YNUser ynUser = new YNUser();
        ynUser.setUnickname("Add成员");
        ynMember.setUser(ynUser);
        mMemberDatas.add(ynMember);
        mAdapter.notifyDataSetChanged();
        String notename = null;
        for (int i = 0; i < memberList.size(); i++) {
            if (memberList.get(i).getUser().getUnickname().equals(chatName)) {
                notename = memberList.get(i).getUser().getNoteName();
            }
        }
        if (!StringUtils.isEmpty(notename)) {
            all_member_zonename.setText(notename);
        } else {
            all_member_zonename.setText(chatName);
        }
    }

    // 分析并执行动作
    BroadcastReceiver mMemberBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                //　加载成员数据
                case ACTIONs.actionMemberUpdate:
                    List<YNMember> memberList = (List<YNMember>) intent.getSerializableExtra(ACTIONs.aAddData);
                    updateView(memberList);
                    break;
                case ACTIONs.actionNoteNameUpdate:
                    noticeServiceInit();
                    break;
            }
        }
    };

    // 注册接收者
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionMemberUpdate);
        myIntentFilter.addAction(ACTIONs.actionNoteNameUpdate);
        registerReceiver(mMemberBroadcastReceiver, myIntentFilter);
    }

    // 通知后台加载数据
    private void noticeServiceInit() {
        Intent mIntent = new Intent(this, AlbumContentService.class);
        mIntent.setAction(ACTIONs.actionAlbumMember);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        startService(mIntent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mMemberBroadcastReceiver);
    }
}
